#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include <signal.h>


int fd;    
char buf[16];

static void read_func(int signum)
{
    u_int32_t recv_cnt = 0;
    memset(buf, 0x00, sizeof(buf));
    recv_cnt = read(fd, buf, sizeof(buf));
    if (recv_cnt < 0)
    {
        printf(" read %d is error: %s\r\n", fd, strerror(errno));
        return ;
    }
    printf("read[%d] : %s\n", strlen(buf), buf);
}


int main(int argc, char *argv[])
{
    int ret;
    int flags;

    if (argc < 2)
    {
        printf("%d\r\n", argc);
        printf("plase input paraments\r\n");
        return -1;
    }

    // 以非阻塞方式打开设备
    fd = open(argv[1], O_RDWR , 0666);
    if (fd < 0)
    {
        
        printf(" open %s is error: %s\r\n", argv[1], strerror(errno));
        return -1;
    }
    printf("open %s is ok\r\n", argv[1]);

    if (argc > 2)
    { 
        if (! strcmp(argv[2], "read"))
        {

            // 注册SIGIO信号
            signal(SIGIO, read_func);
            // 设置能够接收这个信号的进程
            fcntl(fd, __F_SETOWN, getpid());
            // 开启信号驱动IO通常使用fcntl函数的F_SETFL命令打开FASYNC标志。
            flags = fcntl(fd, F_GETFD);
            fcntl(fd, F_SETFL, flags | FASYNC);
            while(1)
            {
                sleep(1);
            }
        } else if (! strcmp(argv[2], "write"))
        {
            if (argc > 3)
            {
                // strncpy(buf, argv[3], strlen(argv[3]));
                write(fd, argv[3], strlen(argv[3]));
            }
            else {
                write(fd, "nihao!!", sizeof("nihao!!"));
            }
            
        }
    }

    close(fd);

    return 0;
}
